using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Xml;

namespace PhilWicklund.com.SiteCreationWorkflow.Data
{
  public abstract class DataObjectBase
  {
    public virtual string ToXml()
    {
      return ToXml(false);
    }

    public virtual string ToXml(bool FormatOutput)
    {
      // suppress the xsi namespace declaration
      XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
      ns.Add("", "");

      XmlSerializer ser = new XmlSerializer(this.GetType());

      // store the serialized object in memory
      MemoryStream memStream = new MemoryStream();
      XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.UTF8);

      // unless we're told, do not format
      xmlWriter.Formatting = Formatting.None;
      if (FormatOutput)
      {
        xmlWriter.Formatting = Formatting.Indented;
      }
      
      ser.Serialize(xmlWriter, this, ns);
      xmlWriter.Close();
      memStream.Close();

      // get the xml in a string
      string xml = Encoding.UTF8.GetString(memStream.GetBuffer());

      // the memory stream likely has unused bytes, so strip everything
      // before the first < and after the last >
      xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
      xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));

      return xml;
    }

    public static object Deserialize(Type objectType, string objectXML)
    {
      XmlSerializer ser;
      ser = new XmlSerializer(objectType);

      StringReader sr = new StringReader(objectXML);
      return ser.Deserialize(sr);
    }

  }
}
